package huang.com.android.alarmserver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.Calendar;

public class alarmService extends AppCompatActivity implements View.OnClickListener {

    private static alarmService appRef = null;
    private Button call_alarm, exit_service;
    boolean k = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alarm_service);
        appRef = this;
        call_alarm = (Button) findViewById(R.id.alarm);
        call_alarm.setOnClickListener(this);
        exit_service = (Button) findViewById(R.id.exit);
        exit_service.setOnClickListener(this);
    }

    public static alarmService getApp(){
        return appRef;
    }

    public void btEvent(String data){
        setTitle(data);
    }

    @Override
    public void onClick(View v) {
        if (v == call_alarm){
            setTitle("Waiting... Alarm=5");
            Intent intent = new Intent(alarmService.this,AlarmReceiver.class);
            PendingIntent p_intent = PendingIntent.getBroadcast(
                    alarmService.this,0,intent,0);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND,3);
            // Schedule the alarm!

            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),p_intent);


        }

        if (v == exit_service){
            Intent intent = new Intent(alarmService.this,AlarmReceiver.class);
            PendingIntent p_intent = PendingIntent.getBroadcast(
                    alarmService.this,0,intent,0);
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.cancel(p_intent);
            finish();

        }
    }
}
